package com.hmall.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.Stock;
import com.hmall.config.ItemConfig;
import com.hmall.config.UserFegin;
import com.hmall.order.interceptor.UserInterceptor;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderDto;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.IOrderService;
import com.hmall.order.service.OrderDetailService;
import com.hmall.order.service.OrderLogisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private ItemConfig itemConfig;
    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private OrderLogisticsService orderLogisticsService;
    @Autowired
    private UserFegin userFegin;

    /**
     *
     * 提交订单
     *
     * **/
    @Override
    public String createOrder(OrderDto orderDto) {
        //根据itemId查询商品信息
        Item item = itemConfig.getbyId(orderDto.getItemId());
        Order order = new Order();
        order.setTotalFee(orderDto.getNum()*item.getPrice());
        order.setStatus(1);
        order.setPaymentType(orderDto.getPaymentType());
        order.setUserId(Long.valueOf(UserInterceptor.getuserbyid()));
        order.setCreateTime(new Date());
        this.save(order);

        OrderDetail orderDetail = BeanUtil.toBean(item, OrderDetail.class);
        orderDetail.setOrderId(order.getId());
        orderDetail.setItemId(item.getId());
        orderDetail.setNum(orderDto.getNum());
        orderDetail.setId(null);
        orderDetail.setTitle(item.getName());


        orderDetailService.save(orderDetail);

        Address address = userFegin.findAddressById(Long.valueOf(orderDto.getAddressId()));

        OrderLogistics orderLogistics = BeanUtil.toBean(address, OrderLogistics.class);
        orderLogistics.setOrderId(order.getId());
        orderLogisticsService.save(orderLogistics);
        Stock stock = new Stock();
        stock.setItemId(item.getId());
        stock.setNum(item.getStock()- orderDto.getNum());
        itemConfig.stock(stock);
        return order.getId().toString();
    }
}
